package com.sinotrans.common.util.property;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sinotrans.common.spring.SpringContextHolder;

/**
 * 基本加载配置文件工具
 * 
 * @author gaofu
 *
 */
public class BaseProperties {
	private static final Logger logger = LoggerFactory.getLogger(BaseProperties.class);

	private static volatile Map<String, Properties> cacheMap = new HashMap<String, Properties>();

	/**
	 * 初始化
	 * 
	 * @param name
	 */
	protected static void init(String name) {
		Properties properties = cacheMap.get(name);
		if (properties == null) {
			synchronized (cacheMap) {
				properties = cacheMap.get(name);
				if (properties == null) {
					properties = new Properties();
					InputStream inputStream = null;
					try {
						inputStream = BaseProperties.class.getResourceAsStream("/" + name);
						properties.load(inputStream);
					} catch (Exception e) {
						logger.error("加载配置文件异常", e);
					} finally {
						if (inputStream != null) {
							try {
								inputStream.close();
							} catch (Exception e) {
								logger.error("关闭文件流异常", e);
							}
						}
					}
					cacheMap.put(name, properties);
				}
			}
		}
	}

	/**
	 * 加载 classpath:/name.properties
	 * 
	 * @param name eg. : application.properties
	 * @return
	 */
	public static Properties load(String name) {
		init(name);
		return cacheMap.get(name);
	}

	/**
	 * <p>
	 * 加载 classpath:/name-${env}.properties
	 * </p>
	 * 如当前环境为 prod (spring.profiles.active=prod), 传入 application.properties, 则自动加载
	 * classpath:/application-prod.properties
	 * 
	 * @param name
	 * @return
	 */
	public static Properties loadActive(String name) {
		String env = SpringContextHolder.getActiveProfile();
		int i = name.lastIndexOf(".properties");
		if (i == -1) {
			return null;
		}
		String prefixName = name.substring(0, i);
		String activeName = prefixName + "-" + env + ".properties";
		init(activeName);
		return cacheMap.get(activeName);
	}

	public static String getBStrapValue(String key) {
		return load("bootstrap.properties").getProperty(key);
	}

	public static String getBStrapActiveValue(String key) {
		return loadActive("bootstrap.properties").getProperty(key);
	}

	public static String getAppValue(String key) {
		return load("application.properties").getProperty(key);
	}

	public static String getAppActiveValue(String key) {
		return loadActive("application.properties").getProperty(key);
	}

	public static String getMsgValue(String key) {
		return load("message.properties").getProperty(key);
	}

	public static String getMsgActiveValue(String key) {
		return loadActive("message.properties").getProperty(key);
	}

}
